package com.gopi.utilities.gui;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;

public class ImageLoader 
{
	
	// better to use WeakReference for image cache..
	private Map<String,ImageIcon> icons;
	private Object LOCK = new Object();
	
	private static ImageLoader _instance = null;
	
	public ImageLoader()
	{
		icons = new HashMap<String,ImageIcon>();
	}
	
	public static ImageLoader getInstance()
	{
		String fp = File.separator;
		if(_instance==null)
		{
			_instance = new ImageLoader();
		}
		return _instance;
	}
	
	public ImageIcon setIcon(String st,ImageIcon icon)
	{
		ImageIcon retIcon;
		synchronized (LOCK) 
		{
			retIcon = icons.get(st);
			icons.put(st,icon);
		}
		return retIcon;
	}
	
	public ImageIcon getIconFromFile(String st)
	{
		synchronized (LOCK) 
		{
			ImageIcon icon = icons.get(st);
			if(icon==null)
			{
				loadIcon(new String[]{st});
			}
			return icons.get(st);
		}
	}
	
	public ImageIcon getIcon(String st)
	{
		synchronized (LOCK) 
		{
			return icons.get(st);
		}

	}
	
	
	public boolean loadDefaultIcon()
	{
		String keys[] = {NewAbstractTreeNode.LEAF_NODE_KEY,NewAbstractTreeNode.EXPANDED_NODE_KEY,
				NewAbstractTreeNode.CLOSED_NODE_KEY,NewAbstractTreeNode.LOADING_NODE_KEY};
		String files[] = new String[keys.length];
		String fp = File.separator;
		for(int i = 0;i<files.length;++i)
		{
			files[i] = "." + fp + "icons" + fp + keys[i] + ".png";
		}
		return loadIcon(keys,files,true);
	}
	
	public boolean loadIcon(String[] keys)
	{
		String files[] = new String[keys.length];
		String fp = File.separator;
		for(int i = 0;i<files.length;++i)
		{
			if(keys[i].indexOf(".")==-1)
				files[i] = "." + fp + "icons" + fp + keys[i] + ".png";
			else
				files[i] = "." + fp + "icons" + fp + keys[i];
		}
		return loadIcon(keys,files,true);
	}
	
	public boolean loadIcon(String[] keys,String[] files,boolean relative)
	{
		boolean status = true;
		if(keys.length!=files.length)
			throw new IllegalArgumentException("Array length doesn't match");
		synchronized (LOCK) 
		{
			try
			{
				int i = 0;
				for(String key : keys)
				{
					System.out.println("Loading ... " + files[i]);
					if(relative)
						icons.put(key,new ImageIcon(this.getClass().getClassLoader().getResource(files[i])));
					else
						icons.put(key,new ImageIcon(files[i]));
					i++;
				}
			}
			catch(Exception e)
			{
				status = false;
			}
		}
		return status;
	}
}
